<template>
    <div class="bg">
        <el-card class="form-card">
            <template #header>
                <div class="card-header">
                    <span>登录</span>
                </div>
            </template>
            <el-form ref="formRef" :model="form" :rules="rules" status-icon label-width="50px">
                <el-form-item label="账号" prop="username">
                    <el-input v-model="form.username" />
                </el-form-item>
                <el-form-item label="密码" prop="password">
                    <el-input v-model="form.password" type="password" show-password />
                </el-form-item>
                <el-form-item>
                    <el-button @click="handleSubmit(formRef)" type="primary">登录</el-button>
                </el-form-item>
            </el-form>
            <el-row justify="space-between">
                <el-col :span="5">
                    <el-link href="/#/register/" type="info">注册账户</el-link>
                </el-col>
                <el-col :span="6">
                    <el-link type="info">忘记密码？</el-link>
                </el-col>
            </el-row>
        </el-card>
    </div>
</template>

<script setup>
    
import { ref, reactive } from 'vue';
// import axios from 'axios';
import Admin from '@/api/admin';
// import { ElMessage } from 'element-plus';
import {useRouter} from 'vue-router';
let form = reactive({
    username: '',
    password: '',
});
// 获取form组件实例对象
let formRef = ref();
//获取router 实例对象
let router = useRouter();
// 表单验证规则
const rules = reactive({
    username: [
        { required: true, message: '请输入账号！', trigger: 'blur' },
        { min: 3, max: 30, message: '账户长度要求3-30个字符之间', trigger: 'blur' },
    ],
    password: [
        { required: true, message: '请输入密码！', trigger: 'blur' },
        { pattern: /\d{3,}/, message: '密码长度至少3位数字', trigger: 'blur' },
    ],
});


// 登录
function handleSubmit(formEl) {
    // 校验整个表单
     formEl.validate(async(valid, fields) => {
        if (valid) {
            // 通过校验
          let {status,msg,data}= await Admin.login({...form})
          if(status){
            //登陆成功
            sessionStorage.id = data.id;
            sessionStorage.role = data.role;
            sessionStorage.token = data.token;
            //跳转页面
            router.push('/admin/list')
          }else{
            //登陆失败
            ElMessage.error(msg)
          }
        
        } else {
            // 校验失败
            console.log('失败字段', fields);
        }
    });
}

</script>

<style lang="less" scoped>
.bg {
    position: relative;
    min-height: 100vh;
    background: url(../assets/img/login/bg.jpg) top center;
    background-size: cover;

    .form-card {
        position: absolute;
        top: 50%;
        right: 30px;
        transform: translateY(-50%);
        width: 360px;
    }
}
</style>
